#include "qspectrogramview.h"
#include "qaudioreader.h"
#include "qaudiorformat.h"
#include "qtimewatch.h"
#include "qspectrogramdrawing.h"

#include <QFileInfo>
#include <QPainter>
#include <QRect>
#include <QLineF>
#include <QPaintEvent>

namespace AudioUtils {

	class QSpectrogramViewPrivate
	{
	public:
		QSpectrogramViewPrivate()
		{
			init();
		}

		~QSpectrogramViewPrivate() 
		{
		}

		void init()
		{
			path = "";
		}

	public:
		QString path;
	};

	QSpectrogramView::QSpectrogramView(QWidget *parent)
		: QWidget(parent)
		, p(new QSpectrogramViewPrivate)
	{
	}

	QSpectrogramView::~QSpectrogramView()
	{
		delete p;
	}

	void QSpectrogramView::open(const QString &path)
	{
		p->path = path;
        update();
    }

	void QSpectrogramView::paintEvent(QPaintEvent *event)
	{
		auto rect = this->rect();
		QPainter painter(this);
		painter.fillRect(rect, Qt::black);
		painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);

		if (p->path.isEmpty() || 
			p->path.isNull()
			)
		{
			return;
		}

		QFileInfo file(p->path);
		if (!file.exists())
		{
			p->init();
			return;
		}

		QTimeWatch watch("draw spectrogram:");
		QString path = file.absoluteFilePath();
		QAudioFormat format;
		if (!format.open(path))
		{
			p->init();
			return;
		}

		QAudioReader reader;
		if (!reader.open(path))
		{
			p->init();
			return;
		}

		QSpectrogramDrawing drawing;
		drawing.draw(painter, format, reader, rect);
    }

}
